import React, { useState, useEffect } from 'react';
import { Button, Row, Col, Form, Input, DatePicker, Radio, Select } from 'antd';
import { FormComponentProps } from 'antd/es/form';
import moment from 'moment';
import { SIZE, PAGE, ALL } from '@/utils/constant';
import { parentsList } from '@/services/api';

interface UserFormProps extends FormComponentProps {
  dispatch: (value: object) => void;
  msgList: (value: object) => void;
}

const { Item } = Form;
const MyForm = Form.create<UserFormProps>()(
  ({ form: { getFieldDecorator, getFieldsValue, resetFields }, msgList, dispatch }: any) => {
    const [parentsData, setParentsData] = useState([]);
    const [msgType, setMsgType] = useState('0');
    const formItemLayout = {
      labelCol: {
        xs: { span: 6 },
      },
      wrapperCol: {
        sm: { span: 18 },
      },
    };

    // 请求家长数据
    useEffect(() => {
      parentsList({ page: PAGE, size: SIZE }).then((resp: any) => {
        if (resp.status === 'success') {
          setParentsData(resp.data.data);
        }
      });
    }, []);

    return (
      <Form {...formItemLayout}>
        <Row gutter={24}>
          <Col span={17}>
            <Item label="消息类型" labelCol={{ span: 2 }}>
              {getFieldDecorator('receive_type', {
                initialValue: '0',
              })(
                <Radio.Group
                  onChange={(e: any) => {
                    setMsgType(e.target.value);
                  }}
                >
                  <Radio value="0">所有消息</Radio>
                  <Radio value="1">个人消息</Radio>
                  <Radio value="2">系统消息</Radio>
                </Radio.Group>,
              )}
            </Item>
          </Col>
        </Row>
        <Row className="rowMarginTop" gutter={24}>
          <Col span={6}>
            <Item label="标题">{getFieldDecorator('title')(<Input placeholder="请输入" />)}</Item>
          </Col>
          <Col span={6}>
            <Item label="创建日期">
              {getFieldDecorator('created_at')(<DatePicker placeholder="请选择" />)}
            </Item>
          </Col>
          <Col span={6}>
            {msgType === '1' && (
              <Item label="接收家长">
                {getFieldDecorator('parent_id')(
                  <Select
                    placeholder="请选择"
                    allowClear
                    showSearch
                    defaultActiveFirstOption={false}
                    filterOption={false}
                    // filterOption={(input: any, option: any) =>
                    //   option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    // }
                    onSearch={value => {
                      if (value) {
                        const searchValue = value.trim();
                        parentsList({ page: PAGE, size: ALL, keyword: searchValue }).then(
                          (resp: any) => {
                            if (resp.status === 'success') {
                              setParentsData(resp.data.data);
                            }
                          },
                        );
                      }
                    }}
                  >
                    {parentsData.map((item: any) => (
                      <Select.Option value={item.id} key={item.id}>
                        {item.name}
                      </Select.Option>
                    ))}
                  </Select>,
                )}
              </Item>
            )}
          </Col>
          <Col offset={2} span={4}>
            <Button
              type="primary"
              onClick={() => {
                let isGetData = false;
                const formValue: object = getFieldsValue();
                const newFormValue = {};
                Object.keys(formValue).forEach((item: string) => {
                  if (formValue[item]) {
                    isGetData = true;
                    if (item === 'created_at') {
                      newFormValue[item] = moment(formValue[item]).format('YYYY-MM-DD');
                    } else if (formValue[item] || formValue[item] === '') {
                      isGetData = true;
                      if (typeof formValue[item] === 'string') {
                        newFormValue[item] = formValue[item].trim();
                      } else {
                        newFormValue[item] = formValue[item];
                      }
                    }
                  }
                });
                if (isGetData) {
                  dispatch({
                    type: 'OPEN_LOADING',
                  });
                  dispatch({
                    type: 'SEARCH_VALUE',
                    payload: newFormValue,
                  });
                  msgList({ ...newFormValue, page: PAGE, size: SIZE })
                    .then((res: any) => {
                      if (res.status === 'success') {
                        dispatch({
                          type: 'GET_DATA',
                          payload: res.data.data,
                        });
                        dispatch({
                          type: 'CHANGE_PAGINATION',
                          payload: {
                            current: PAGE,
                            pageSize: SIZE,
                            showSizeChanger: true,
                            total: res.data.meta.total,
                          },
                        });
                      }
                      dispatch({
                        type: 'CLOSED_LOADING',
                      });
                    })
                    .catch(() => {
                      dispatch({
                        type: 'CLOSED_LOADING',
                      });
                    });
                }
              }}
            >
              查询
            </Button>
            <Button
              className="secondBtn"
              onClick={() => {
                resetFields();
                setMsgType('0');
                dispatch({
                  type: 'OPEN_LOADING',
                });
                msgList({ page: PAGE, size: SIZE })
                  .then((res: any) => {
                    if (res.status === 'success') {
                      dispatch({
                        type: 'GET_DATA',
                        payload: res.data.data,
                      });
                      dispatch({
                        type: 'CHANGE_PAGINATION',
                        payload: {
                          current: PAGE,
                          pageSize: SIZE,
                          showSizeChanger: true,
                          total: res.data.meta.total,
                        },
                      });
                      dispatch({
                        type: 'SEARCH_VALUE',
                        payload: {},
                      });
                    }
                    dispatch({
                      type: 'CLOSED_LOADING',
                    });
                  })
                  .catch(() => {
                    dispatch({
                      type: 'CLOSED_LOADING',
                    });
                  });
              }}
            >
              重置
            </Button>
          </Col>
        </Row>
      </Form>
    );
  },
);

export default MyForm;
